<?php
	defined('RUN') or die('No access');

	class PostModel
	{
		private $tables='posts';
		public function getByPage($fields='*', $page, $per_page = 20)
		{
			$order = '`updated` DESC, `id` DESC';
			$conditions='';
			$offset = ($page - 1) * $per_page;
			$data = Model::getData($this->tables, $fields, $conditions, $per_page, $offset, $order);
			return $data;
		}
		public function getPost($fields='*')
		{
			return Model::getDataSql("SELECT ".$fields." FROM ".$this->tables." ORDER BY `updated` DESC, `id` DESC");
		}
		public function getLastest($limit = 3)
		{
			$order = array(
					'field' => 'id',
					'type' => 'DESC'
				);

			$posts = Model::getData($this->tables, '*', '', $limit, 0, $order);

			return $posts;	
		}

		public function getTotalRows()
		{
			$sql = "SELECT COUNT(`id`) as `total` FROM ".$this->tables;
			$query = Db::query($sql);
			$row = Query::fetch($query);

			return $row['total'];
		}

		public function getById($id, $filed='*')
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			$post = Model::getData($this->tables, $filed, $condition);

			if ($post)
				return $post[0];

			return FALSE;
		}
		public function getRelated($fields='*', $idcat, $id, $limit=10)
		{
			return Model::getDataSql("SELECT ".$fields." FROM ".$this->tables." WHERE `category_id`=".$idcat." AND `id` != ".$id." ORDER BY `updated` ASC, `id` DESC LIMIT 0,".$limit);
		}
		public function getByCategory($cat_id)
		{
			$condition = array(
					'field' => 'category_id',
					'value' => $cat_id
				);

			$posts = Model::getData($this->tables, '*', $condition);

			return $posts;
		}

		public function getByPlace($place_id)
		{
			$condition = array(
					'field' => 'place',
					'value' => $place_id
				);

			$posts = Model::getData($this->tables, '*', $condition);

			return $posts;
		}

		public function add($post)
		{
			return Model::insertData($this->tables, $post);
		}

		public function update($post, $id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);
			
			return Model::updateData($this->tables, $post, $condition);
		}

		public function delete($id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			return Model::deleteData($this->tables, $condition);
		}
	}
